//
//  Image.m
//  MOSAD_HW3
//
//  Created by enrique leo on 2020/12/15.
//

#import <Foundation/Foundation.h>
#import "Image.h"
//#import "Cache.h"
#import "Masonry.h"
#import "AFNetworking.h"

//extern Cache *imageCache;

@implementation Image

- (void)viewDidLoad{
    self.navigationItem.title = @"图片浏览";
    self.view.backgroundColor = [UIColor colorWithRed:15/255.0 green:135/255.0 blue:219/255.0 alpha:1];
    
    self.clean = [[UIButton alloc]init];
    self.clean.backgroundColor = [UIColor colorWithRed:22/255.0 green:219/255.0 blue:39/255.0 alpha:1];
    [self.clean setTitle:@"清空" forState:(UIControlStateNormal)];
    self.clean.titleLabel.font = [UIFont systemFontOfSize: 22];
    self.clean.layer.cornerRadius = 10;
    self.clean.layer.masksToBounds = YES;
    [self.clean addTarget:self action:@selector(onClickClean) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:self.clean];
    UIEdgeInsets padding = UIEdgeInsetsMake(0, 0, 100, 0);
    [self.clean mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view.mas_bottom).with.offset(-padding.bottom);
        make.centerX.equalTo(self.view.mas_centerX).with.offset(0);
        make.width.mas_equalTo(100);
        make.height.mas_equalTo(40);
    }];
    
    self.load = [[UIButton alloc]init];
    self.load.backgroundColor = [UIColor colorWithRed:22/255.0 green:219/255.0 blue:39/255.0 alpha:1];
    [self.load setTitle:@"加载" forState:(UIControlStateNormal)];
    self.load.titleLabel.font = [UIFont systemFontOfSize: 22];
    self.load.layer.cornerRadius = 10;
    self.load.layer.masksToBounds = YES;
    [self.load addTarget:self action:@selector(onClickLoad) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:self.load];
    padding = UIEdgeInsetsMake(0, 30, 100, 0);
    [self.load mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view.mas_bottom).with.offset(-padding.bottom);
        make.right.equalTo(self.clean.mas_left).with.offset(-padding.left);
        make.width.mas_equalTo(100);
        make.height.mas_equalTo(40);
    }];
    
    self.deleteCache = [[UIButton alloc]init];
    self.deleteCache.backgroundColor = [UIColor colorWithRed:22/255.0 green:219/255.0 blue:39/255.0 alpha:1];
    [self.deleteCache setTitle:@"删除缓存" forState:(UIControlStateNormal)];
    self.deleteCache.titleLabel.font = [UIFont systemFontOfSize: 22];
    self.deleteCache.layer.cornerRadius = 10;
    self.deleteCache.layer.masksToBounds = YES;
    [self.deleteCache addTarget:self action:@selector(onClickDelectCache) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:self.deleteCache];
    padding = UIEdgeInsetsMake(0, 0, 100, 30);
    [self.deleteCache mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view.mas_bottom).with.offset(-padding.bottom);
        make.left.equalTo(self.clean.mas_right).with.offset(padding.right);
        make.width.mas_equalTo(100);
        make.height.mas_equalTo(40);
    }];
    
    //创建flowLayout
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    //行与行间的距离
    flowLayout.minimumLineSpacing = 10;
    //列与列间的距离
    flowLayout.minimumInteritemSpacing = 10;
    //设置item的大小
    //CGFloat size =  self.view.frame.size.width / 3;
    flowLayout.itemSize = CGSizeMake(150, 150);
    flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);

    //self.testText = [NSMutableArray arrayWithObjects:@"one",@"two",@"three",@"four",@"five", nil];
    //创建集合视图
     self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"customCollectionCell"];
    [self.view addSubview: self.collectionView];
    padding = UIEdgeInsetsMake(150, 10, 100, 30);
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).with.offset(padding.top);
        make.width.mas_equalTo(self.view.mas_width);
        make.height.mas_equalTo(400);
    }];
}

- (void) onClickLoad{
    if(self.imageCache == nil){
        self.imageCache = [[Cache alloc]init];
    }
    
    NSMutableArray *imageURLs = [[NSMutableArray alloc]init];
    [imageURLs addObject:@"https://hbimg.huabanimg.com/d8784bbeac692c01b36c0d4ff0e072027bb3209b106138-hwjOwX_fw658"];
    [imageURLs addObject:@"https://hbimg.huabanimg.com/6215ba6f9b4d53d567795be94a90289c0151ce73400a7-V2tZw8_fw658"];
    [imageURLs addObject:@"https://hbimg.huabanimg.com/834ccefee93d52a3a2694535d6aadc4bfba110cb55657-mDbhv8_fw658"];
    [imageURLs addObject:@"https://hbimg.huabanimg.com/f3085171af2a2993a446fe9c2339f6b2b89bc45f4e79d-LacPMl_fw658"];
    [imageURLs addObject:@"https://hbimg.huabanimg.com/e5c11e316e90656dd3164cb97de6f1840bdcc2671bdc4-vwCOou_fw658"];
    [self getImage: imageURLs];
}

- (void) onClickClean{
    self.loadedCount = 0;
    [self.collectionView reloadData];
}

- (void) onClickDelectCache{
    [self.imageCache removeALL];
    self.loadedCount = 0;
    [self.collectionView reloadData];
}

- (void) getImage: (NSMutableArray*)imageURLs{
    CAReplicatorLayer *replicatorLayer = [self loadingAction];
    [self.view.layer addSublayer:replicatorLayer];
    self.loadedCount = 0;
    for(int i = 0; i < imageURLs.count; i++){
        NSString *itImageURL = [imageURLs objectAtIndex:i];
        NSData *data = self.imageCache.imageDatas[itImageURL];
        if(data){
            NSLog(@"数据已在缓存中");
            self.loadedCount++;
            if(self.loadedCount == imageURLs.count){
                [self.collectionView reloadData];
                [replicatorLayer removeFromSuperlayer];
            }
            continue;
        }else{
            // 图片不在缓存中
            NSString *file = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent: [itImageURL lastPathComponent]];
            data = [NSData dataWithContentsOfFile:file];
            if(data){
                NSLog(@"数据在沙盒中");
                self.imageCache.imageDatas[itImageURL] = data;
                [self.imageCache.imageUrls addObject:itImageURL];
                self.loadedCount++;
                if(self.loadedCount == imageURLs.count){
                    [self.collectionView reloadData];
                    [replicatorLayer removeFromSuperlayer];
                }
            }else{
                // 数据不在沙盒中
                NSLog(@"请求网络下载");
                NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
                AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
                NSURL *URL = [NSURL URLWithString: itImageURL];
                NSURLRequest *request = [NSURLRequest requestWithURL:URL];
                NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
                    // 写入caches目录
                    NSURL *cachesDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSCachesDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
                    dispatch_sync(dispatch_get_main_queue(), ^{
                        // 从沙盒中取
                        NSData* imageData = [NSData dataWithContentsOfURL:targetPath];

                        // 将图片数据存入缓存中
                        self.imageCache.imageDatas[itImageURL] = imageData;
                        [self.imageCache.imageUrls addObject:itImageURL];
                        self.loadedCount++;
                        // 如果已经加载指定数量的图片。loading结束
                        if (self.loadedCount == imageURLs.count) {
                            [self.collectionView reloadData];
                            [replicatorLayer removeFromSuperlayer];
                        }
                    });
                    return [cachesDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
                } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
                    NSLog(@"File downloaded to: %@", filePath);
                }];
                [downloadTask resume];
            }
        }
    }
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.loadedCount;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    NSString* url = [self.imageCache.imageUrls objectAtIndex:indexPath.item];
    //NSLog(@"cache %@ %@", self.imageCache.imageUrls, self.imageCache.imageDatas);
    UIImage *image = [UIImage imageWithData: self.imageCache.imageDatas[url]];
    UIImageView *imgView = [[UIImageView alloc] initWithImage:image];
    
    imgView.frame = CGRectMake(0, 0, 150, 150);
    imgView.layer.borderColor = [UIColor blackColor].CGColor;
    imgView.layer.borderWidth = 1;
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"customCollectionCell" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
    [cell addSubview: imgView];
    return cell;
}

- (CAReplicatorLayer *) loadingAction{
    CAReplicatorLayer *replicatorLayer = [CAReplicatorLayer layer];
    replicatorLayer.bounds = CGRectMake(0, 0, 100, 100);
    replicatorLayer.cornerRadius = 10.0;
    replicatorLayer.position =  self.view.center;
    replicatorLayer.backgroundColor = [UIColor colorWithRed:0.1 green:0.1 blue:0.1 alpha:0.2].CGColor;
    CALayer *dotLayer = [CALayer layer];
    dotLayer.bounds = CGRectMake(0, 0, 15, 15);
    dotLayer.position = CGPointMake(15, replicatorLayer.frame.size.height/2 );
    dotLayer.backgroundColor = [UIColor colorWithRed:0.1 green:0.1 blue:0.1 alpha:0.6].CGColor;
    dotLayer.cornerRadius = 7.5;
    
    CGFloat count =  10.0;
    replicatorLayer.instanceCount = count;
    CGFloat angel = 2* M_PI/count;
    replicatorLayer.instanceTransform = CATransform3DMakeRotation(angel, 0, 0, 1);
    
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
        animation.duration    = 1.0;
        animation.fromValue   = @1;
        animation.toValue     = @0;
        animation.repeatCount = MAXFLOAT;
    dotLayer.transform = CATransform3DMakeScale(0, 0, 0);
    replicatorLayer.instanceDelay = 1.0/10;
    [dotLayer addAnimation:animation forKey:nil];
    [replicatorLayer addSublayer:dotLayer];
    return replicatorLayer;
}

@end
